package yiguan;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import java.util.Properties;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.IOException;
import java.sql.SQLException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.Logger;


public class XingServlet extends HttpServlet {
  private Logger logger = Logger.getLogger(this.getClass());
  private Properties bundleMsg = new Properties();

  public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setCharacterEncoding("UTF-8");
    String action = request.getParameter("action");
    if (isEmpty(action)) {
    	logger.error("action is null");
    	response.getWriter().print("error url parameters");
    	response.getWriter().close();
    	return;
    }

	debugParameters(request);
	response.setContentType("text/json;charset=UTF-8");
	int actionKey;
    try {
    	actionKey = Integer.parseInt(action);
    } catch (NumberFormatException e) {
    	responseMessage(-1, "Invalid URL: action=" + action, response);
    	return;
    }

    switch (actionKey) {
    	case 0 : waiterSignin(request, response); break;
    	case 1 : waiterRegister(request, response); break;
    	case 2 : waiterManage(request, response); break;
    	case 3 : tasksManage(request, response); break;
    	case 4 : customerManage(request, response); break;
    	case 5 : assignedTaskGrid(request, response); break;
    	case 6 : processTask(request, response); break;
    	case 7 : flowsAll(request, response); break;
    	case 8 : withdrawTask(request, response); break;
    	case 9 : allocInfo(request, response); break;
    	case 10: govuserManage(request, response); break;
    	case 11: buildWaiterSelect(response); break;
    	case 12: customerTaskGrid(request, response); break;
    	case 13: companyManage(request, response); break;
    	case 14: buildCompanySelect(response); break;
    	case 15: allocManage(request, response); break;
    	case 16: xgUserManage(request, response); break;
    	case 17: changePass(request, response); break;
    	case 18: userLogin(request, response); break;
    	case 19: allocDistrictInfo(request, response); break;
    	case 20: userExit(request, response); break;
    	case 21: validateCode(request, response); break;
    	case 22: quitCustomerManage(request, response); break;
    	case 23: netMapManage(request, response); break;
    	case 24: queryCustomerByTel(request, response); break;
    	case 25: districtCustomerStat(request, response); break;
    	case 26: zeroAccount(request, response); break;
    	case 27: updateCustomerRemark(request, response); break;
    	default: responseMessage(1, "invalid action : " + action, response);
    }
  }

  private void responseMessage(int code, String message, HttpServletResponse response) {
    JSONObject so = new JSONObject();
	try {
		response.setContentType("text/json;charset=UTF-8");
		so.put("code", code);
		so.put("message", message);
		response.getWriter().print(so.toString());
		response.getWriter().close();
	} catch(Exception e) {
		logger.error(e.getMessage(), e);
	}
  }

  /*
  ** Process task, including querying the account and paying.
  */

  private void processTask(HttpServletRequest request, HttpServletResponse response) {
	String imei = request.getParameter("imei");
	String cid  = request.getParameter("cid");
	String payment = request.getParameter("payment");
	String cash = request.getParameter("cash");
	String taskid = request.getParameter("taskid");
	Customer customer = null;

	JSONObject retval = null;

	if (isEmpty(imei) || isEmpty(cid) ||isEmpty(taskid)) {
		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
	}

	customer = Customer.getCustomerByID(cid);
	if (customer == null) {
		responseMessage(-1, bundleMsg.getProperty("CUSTOMER_NOT_FOUND") + " : cid=" + cid, response);
		return;
	}

	if (payment == null) { //first query customer info, if there is a task then process it.
		retval = customer.toJSON();
		DBUtil.pickupTask(imei, taskid, cid);
	} else {				//payment
		if (cash == null) cash = "0";
		int payment1 = Integer.parseInt(payment);
		int cash1 = Integer.parseInt(cash);
		if (customer.getCursum() < payment1) {
			responseMessage(-2, bundleMsg.getProperty("CUSTOMER_NOT_ENOUGH") + " : cid=" + cid, response);
			return;
		}

		String tid = DBUtil.finishTask(imei, taskid, customer, payment1, cash1);
		if (tid == null) {
			responseMessage(-1, bundleMsg.getProperty("TASK_NOT_FOUND") + " : taskid=" + taskid, response);
			return;
		}

		retval = Task.getTaskByID(taskid);
		customer = Customer.getCustomerByID(cid);
		try {
			retval.put("account", String.valueOf(customer.getCursum()));   //add account field to this task
		} catch (JSONException e) {}
	}

	if (retval != null) {
		try {
			response.getWriter().print(retval);
	  		response.getWriter().close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	} else {
		responseMessage(-1, bundleMsg.getProperty("CUSTOMER_NOT_FOUND"), response);
	}
  }

  private void withdrawTask(HttpServletRequest request, HttpServletResponse response) {
  	String imei = request.getParameter("imei");
  	String taskid = request.getParameter("taskid");
  	String cid = null;

  	if (isEmpty(imei) || isEmpty(taskid)) {
		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
	}

	int retval = DBUtil.withdrawTask(imei, taskid);

	if (retval == 1) {
		responseMessage(1, bundleMsg.getProperty("TASK_NOT_FOUND"), response);
		return;
	} else if (retval == 2) {
		responseMessage(2, bundleMsg.getProperty("TASK_WITHDRAW_WRONG"), response);
		return;
	} else if (retval == -1) {
		responseMessage(-1, "internal error", response);
		return;
	}

	JSONObject task = Task.getTaskByID(taskid);
	try {
		cid = (String)task.get("cid");
		Customer customer = Customer.getCustomerByID(cid);
		task.put("account",customer.getCursum());
		response.getWriter().print(task);
		response.getWriter().close();
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
	}
  }

  /*
  ** Action functions
  */

  //action=2
  private void waiterManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		waiterAll(request, response);
  	else if (oper.equals("edit"))
  		waiterUpdate(request, response);
  	else if (oper.equals("del"))
  		WaiterDelete(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void waiterAll(HttpServletRequest request, HttpServletResponse response) {
  	String mobile  = request.getParameter("mobile");
  	String comid = request.getParameter("comid");

  	Hashtable<String, String> params = new Hashtable<String, String>();
  	if (!isEmpty(mobile))
  		params.put("mobile", mobile);
  	if (!isEmpty(comid) && comid.length() > 1)
  		params.put("comid", comid);

  	Waiter[] ws = Waiter.getAllWaiter(params);
  	JSONArray sa = new JSONArray();
  	JSONObject retval = new JSONObject();

  	for (int i = 0; i < ws.length; i++)
  		sa.put(ws[i].toJSON());

  	try {
  		retval.put("page", 1);
	  	retval.put("total", 1);
	  	retval.put("records", ws.length);
	  	retval.put("rows", sa);

	  	response.getWriter().print(retval);
	  	response.getWriter().close();
  	} catch(Exception e) {}
  }

  private void waiterUpdate(HttpServletRequest request, HttpServletResponse response) {
  	String imei  = request.getParameter("id");
  	String wname = request.getParameter("wname");
  	String mobile = request.getParameter("mobile");
  	String idcard = request.getParameter("idcard");
  	String comid = request.getParameter("comid");
  	String state =  request.getParameter("state");

	Waiter waiter = new Waiter(imei);
  	if (waiter.update(wname, mobile, idcard, comid, Integer.parseInt(state))) {
  		String rmsg = wname + "," + bundleMsg.getProperty("WAITER_UPDATE");
  		//sendOneSMS(mobile, rmsg);
  		responseMessage(0, rmsg, response);
  	} else
  		responseMessage(2, "no record found", response);
  }

  private void WaiterDelete(HttpServletRequest request, HttpServletResponse response) {
  	String imei = request.getParameter("id");

  	if (Waiter.deleteWaiterByMobile(imei)) {
  		logger.info(imei + " deleted!");
  		responseMessage(0, bundleMsg.getProperty("WAITER_DELETE"), response);
  	} else
  		responseMessage(1, "can't found waiter: " + imei, response);
  }

  private void waiterSignin(HttpServletRequest request, HttpServletResponse response) {
  	String imei = request.getParameter("imei");
  	if (isEmpty(imei)) {
  		responseMessage(-1, "null imei", response);
  		return;
  	}

  	Waiter waiter = Waiter.getWaiterByImei(imei);
  	if (waiter == null) {
  		responseMessage(1, bundleMsg.getProperty("MOBILE_NOT_FIND"), response);
  		return;
  	}
  	logger.info(waiter.getWname() + " signedin with mobile: " + waiter.getMobile());

  	if (waiter.getState() == 0) {
  		responseMessage(2, bundleMsg.getProperty("MOBILE_NOT_ACCEPT"), response);
  		return;
  	} else if(waiter.getState() == 2) {
  		responseMessage(3, bundleMsg.getProperty("MOBILE_NOT_ENABLE"), response);
  		return;
  	}

  	JSONArray tasks = Task.getAssignedTaskList(waiter.getMobile());
  	JSONObject so = new JSONObject();
   	try{
   		so.put("code", 0);
   		so.put("message", "ok");
   		so.put("tasks", tasks);
   		response.setContentType("text/json;charset=UTF-8");
   		response.getWriter().print(so.toString());
   		response.getWriter().close();
   	} catch(Exception e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void waiterRegister(HttpServletRequest request, HttpServletResponse response) {
  	String imei = request.getParameter("imei");
  	String wname = request.getParameter("wname");
  	String mobile = request.getParameter("mobile");
  	if (isEmpty(imei) || isEmpty(wname) || isEmpty(mobile)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

	Waiter waiter = new Waiter(wname, mobile, imei);
  	if (waiter.register()) {
  		logger.info(wname + " registered with mobile " + mobile + " and imei: " + imei);
  		responseMessage(0, bundleMsg.getProperty("MOBILE_REGISTERED"), response);
  	}
  }

  //action=3
  private void tasksManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		tasksAll(request, response);
  	else if (oper.equals("add"))
  		tasksAdd(request, response);
  	else if (oper.equals("edit"))
  		tasksAssign(request, response);
  	else if (oper.equals("del"))
  		taskDel(request, response);
  	else if (oper.equals("end"))
  		taskEnd(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void tasksAll(HttpServletRequest request, HttpServletResponse response) {
  	String page = request.getParameter("page");
  	String comid = request.getParameter("comid");
  	String state = request.getParameter("state");
  	String rectime = request.getParameter("rectime");

  	Hashtable<String, String> params = new Hashtable<String, String>();
  	if ((comid != null) && (comid.length() > 1))
  		params.put("comid", comid);
  	if ((state != null) && (!state.equals("9")))
  		params.put("state", state);
  	if (rectime != null)
  		params.put("rectime", rectime);

	int p = Integer.parseInt(page);
  	JSONObject grid = Task.getAllTask(params, p);

  	try {
  		response.getWriter().print(grid);
  		response.getWriter().close();
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
   }

  private void assignedTaskGrid(HttpServletRequest request, HttpServletResponse response) {
   	String smobile = request.getParameter("mobile");
   	String page = request.getParameter("page");

   	int p = Integer.parseInt(page);
   	JSONObject grid = Task.getAssignedTaskGrid(smobile, p);
   	try{
   		response.getWriter().print(grid);
   		response.getWriter().close();
   	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void customerTaskGrid(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("cid");
  	String page = request.getParameter("page");

  	int p = Integer.parseInt(page);
   	JSONObject grid = Task.getCustomerTaskGrid(cid, p);
   	try{
   		response.getWriter().print(grid);
   		response.getWriter().close();
   	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void tasksAdd(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("cid");
  	String cname = request.getParameter("cname");
  	String csex = request.getParameter("csex");
  	String cservice = request.getParameter("cservice");
  	String note = request.getParameter("note");
  	String ordertime = request.getParameter("ordertime");
  	String cmobile = request.getParameter("cmobile");
  	String ctel = request.getParameter("ctel");
  	String ctype = request.getParameter("ctype");
  	String caddress = request.getParameter("caddress");
  	String uid=(String) request.getSession().getAttribute("uid");

  	if (isEmpty(cid)||isEmpty(cname)||isEmpty(csex)||isEmpty(cservice)||isEmpty(caddress)) {
  			responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  			return;
  	}

  	if (note == null) note = "";
  	if (cmobile == null) cmobile = "";
  	if (ctel == null) ctel = "";
  	if (ordertime == null) ordertime = "";

  	if (Task.addTask(cid, cname, csex, ctype, cservice, note, ordertime, cmobile, ctel, caddress, uid))
  		responseMessage(0, "OK", response);
  	else
  		responseMessage(1, "internal error", response);
  }

  private void tasksAssign(HttpServletRequest request, HttpServletResponse response) {
  	String sname = request.getParameter("sname");
  	String taskid = request.getParameter("taskid");
  	String ordertime = request.getParameter("ordertime");
  	String cname = request.getParameter("cname");
  	String cmobile = request.getParameter("cmobile");
  	String caddress = request.getParameter("caddress");
  	String ctel = request.getParameter("ctel");
  	String uid=(String) request.getSession().getAttribute("uid");

  	if (isEmpty(sname)||isEmpty(taskid)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	int sp = sname.indexOf(":");
  	String smobile = sname.substring(sp + 1);
  	sname = sname.substring(0, sp);

	Task task = new Task(taskid);
	Waiter waiter = Waiter.getWaiterByMobile(smobile);
  	if (task.assign(waiter, ordertime, uid)) {
  		String cmsg = bundleMsg.getProperty("CUSTOMER_NOTIFY") + sname + " " + smobile;
  		String smsg = bundleMsg.getProperty("WAITER_NOTIFY") + cname + " " + caddress + " " + cmobile + " " + ctel;
  		//sendSMSofAssignTask(cmobile, smobile, cmsg, smsg);
  		responseMessage(0, "OK", response);
  	} else
  		responseMessage(2, "internal error", response);
  }

  private void taskDel(HttpServletRequest request, HttpServletResponse response) {
  	String taskid = request.getParameter("id");

  	if (isEmpty(taskid)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	if (Task.deleteTaskByID(taskid))
  		responseMessage(0, "OK", response);
  	else
  		responseMessage(2, "internal error", response);
  }
  
  private void taskEnd(HttpServletRequest request, HttpServletResponse response) {
  	String taskid = request.getParameter("taskid");
  	
  	if (isEmpty(taskid)) {
  		responseMessage(-1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}
  	
  	int rownum = Task.setEndState(taskid);
  	responseMessage(rownum, "internal error", response);
  }

  private void flowsAll(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");
  	String page = request.getParameter("page");
  	String comid = request.getParameter("comid");
  	String wname = request.getParameter("wname");
  	String cid = request.getParameter("cid");
  	String cname = request.getParameter("cname");
  	String recdate = request.getParameter("recdate");
  	String district = request.getParameter("district");
  	String sid = request.getParameter("sid");
  	String commuid = request.getParameter("commuid");
  	String ctype = request.getParameter("ctype");
  	String  uid=(String) request.getSession().getAttribute("uid");

  	if ((uid != null) && (uid.startsWith("1307")) && (!uid.equals("130700"))) {
  		district = (String) request.getSession().getAttribute("udistrict");
  	}

  	JSONObject retval = null;

  	int page_ = 0;
  	try {
  		page_ = Integer.parseInt(page);
  	} catch (Exception e) {}

  	Hashtable<String, String> params = new Hashtable<String, String>();
  	if (!isEmpty(comid) && (comid.length() > 1))
  		params.put("comid", comid);
  	if (!isEmpty(wname))
  		params.put("wname", wname);
  	if (!isEmpty(cid) && (cid.length() > 2))
  		params.put("cid", cid);
  	if (!isEmpty(cname))
  		params.put("cname", cname);
  	if (!isEmpty(recdate))
  		params.put("recdate", recdate);
  	if (!isEmpty(district) && (!district.equals("0")))
  		params.put("district", district);
  	if (!isEmpty(sid) && (sid.length() > 1))
  		params.put("sid", sid);
  	if (!isEmpty(commuid) && (commuid.length() > 1))
  		params.put("commuid", commuid);
  	if (!isEmpty(ctype) && !ctype.equals("0"))
  		params.put("ctype", ctype);

  	if (oper == null)
  		retval = DBUtil.flowAll(page_, params);
  	else if (oper.equals("sum"))
  		retval = DBUtil.flowSum(page_, params);
  	else if (oper.equals("sumexcel")) {
  		DBUtil.flowsumExcel(params, response);
  		return;
  	}
  	else if (oper.equals("ledger"))
  		retval = DBUtil.ledgerStat(page_, params);
  	else if (oper.equals("ledgerexcel")) {
  		DBUtil.ledgerExcel(params, response);
  		return;
  	}


  	try {
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  //action=4
  private void customerManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if ((oper == null) || (oper.equals("excel")))
  		customerAll(request, response);
  	else if (oper.equals("add")||(oper.equals("edit")))
  		customerAdd(request, response);
  	else if (oper.equals("del"))
  		customerDel(request, response);
  	else if (oper.equals("query"))
  		customerQuery(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void customerAll(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");
  	String page = request.getParameter("page");
  	String rows = request.getParameter("rows");
  	String district = request.getParameter("sf_district");
  	String sid = request.getParameter("sf_street");
  	String commuid = request.getParameter("sf_community");
  	String ctype = request.getParameter("sf_ctype");
  	String cid   = request.getParameter("sf_cid");
  	String idcard = request.getParameter("sf_idcard");
  	String cname = request.getParameter("sf_cname");
  	String cage  = request.getParameter("sf_cage");
  	String isquit = request.getParameter("isquit");
  	String uid=(String) request.getSession().getAttribute("uid");
  	Object usid;

  	if ((uid != null) && (uid.startsWith("1307")) && (!uid.equals("130700"))) {
  		district = (String) request.getSession().getAttribute("udistrict");
  	}
  	int p = 1, r = 20;

  	Hashtable<String, String> params = new Hashtable<String, String>();
  	if ((district != null) && (!district.equals("0")))
  		params.put("district", district);
  	if ((sid != null) && (sid.length() > 1))
  		params.put("sid", sid);
  	if ((commuid != null) && (commuid.length() > 1))
  		params.put("commuid", commuid);
  	if ((ctype != null) && (!ctype.equals("0")))
  		params.put("ctype", ctype);
  	if ((cid != null) && (cid.length() > 2))
  		params.put("cid", cid);
  	if ((idcard != null) && (idcard.length() > 1))
  		params.put("idcard", idcard);
  	if ((cname != null) && (cname.length() > 0))
  		params.put("cname", cname);
  	if ((isquit != null) && (isquit.length() == 1))
  		params.put("isquit", isquit);
  	if ((cage != null) && (cage.length() > 1))
  		params.put("year(current_date) - cbirth", cage);
  	
  	usid = request.getSession().getAttribute("usid");
  	if ((usid != null) && (!usid.equals("0")))
  		params.put("sid", (String)usid);

  	JSONObject grid = null;
  	int iuser = 0;

  	try {
  		p = Integer.parseInt(page);
  		r = Integer.parseInt(rows);
  		iuser = Integer.parseInt(uid);
  	} catch(Exception e) {}

  	if (oper == null) {
  		grid = Customer.getAllCustomer(params, p, r);
  	} else if (oper.equals("excel")) {
  		Customer.toExcel(params, response);
  		return;
  	}

  	try {
  		JSONObject userData = null;
  		userData = (JSONObject)grid.get("userdata");
  		if (userData == null)
  			userData = new JSONObject();
  		userData.put("udistrict", (String)request.getSession().getAttribute("udistrict"));
  		userData.put("usid", (String)request.getSession().getAttribute("usid"));
  		grid.put("userdata", userData);
  		response.getWriter().print(grid);
  		response.getWriter().close();
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	} catch(JSONException e1) {}
  }

  private void customerAdd(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");
  	String cid = request.getParameter("cid");
  	String cname = request.getParameter("cname");
  	String csex = request.getParameter("csex");
  	String ctype = request.getParameter("ctype");
  	String idcard = request.getParameter("idcard");
  	String cmobile = request.getParameter("cmobile");
  	String ctel = request.getParameter("ctel");
  	String caddress = request.getParameter("caddress");
  	//String cursum = request.getParameter("cursum");
  	String subsidy = request.getParameter("subsidy");
  	String district = request.getParameter("district");
  	String sid = request.getParameter("sid");
  	String commuid = request.getParameter("commuid");
  	String nationality = request.getParameter("nationality");
  	String family = request.getParameter("family");
  	String health = request.getParameter("health");
  	String residence = request.getParameter("residence");

  	if(isEmpty(cid)||isEmpty(subsidy)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	/*
  	 * for zjk, allocing has no time cost.
  	 *if (DBUtil.isAllocing()) {
  		responseMessage(1000, bundleMsg.getProperty("CUSTOMER_ALLOCING"), response);
  		return;
  	}
  	*/

	int r = -1;
	Customer customer = new Customer(cid);
	customer.set(cname, csex, ctype, idcard, cmobile,ctel, caddress, Integer.parseInt(subsidy),
		district, sid, commuid,nationality,family,health,residence);
  	if (oper.equals("add")) {
  		r = customer.saveNewToDB();
  		if(r == 0)
  			responseMessage(0, "OK", response);
  		else
  			responseMessage(r, "internal error", response);
  	} else {
		r = customer.update();
		if(r == 0)
  			responseMessage(0, "OK", response);
  		else
  			responseMessage(r, "internal error", response);
  	}
  }

  private void customerDel(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("id");

  	if (isEmpty(cid)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	/*
  	 * for zjk, allocing has no time cost.
  	 *
  	if (DBUtil.isAllocing()) {
  		responseMessage(1000, bundleMsg.getProperty("CUSTOMER_ALLOCING"), response);
  		return;
  	}
  	*/

  	if(Customer.quitCustomerByID(cid))
  		responseMessage(0, "OK", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void allocManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		allocStat(request, response);
  	else if (oper.equals("del") || oper.equals("alloc"))	// 'del' operation is used to alloc
  		allocCustomer(request, response);
  	else if (oper.equals("excel"))
  		Customer.statExcel(response);
  }

  private void allocStat(HttpServletRequest request, HttpServletResponse response) {
  	JSONObject retval = new JSONObject();
  	JSONArray cs = Customer.getCustomerStatInfo();

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", cs.length());
  		retval.put("rows", cs);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void allocCustomer(HttpServletRequest request, HttpServletResponse response) {
  	String district = request.getParameter("district");
  	int r = -1;

  	if (district == null)
  		r = Customer.alloc();
  	else
  		r = Customer.allcoDistrict(district);

  	if (r == 0)
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(r, "internal error", response);
  }
  
  //action = 25
  private void districtCustomerStat(HttpServletRequest request, HttpServletResponse response) {
  	String udistrict = (String) request.getSession().getAttribute("udistrict");
  	String oper = request.getParameter("oper");
  	String month = request.getParameter("id");
  	JSONObject retval = new JSONObject();
  	
  	if ((oper != null) && oper.equals("sub")) {
  		JSONArray scs = Customer.getStreetCustomerStat(udistrict, month);
  		try {
  			retval.put("page", 1);
	  		retval.put("total", 1);
	  		retval.put("records", scs.length());
	  		retval.put("rows", scs);
	  		response.getWriter().print(retval);
	  		response.getWriter().close();
  		} catch(JSONException e) {
	  		logger.error(e.getMessage(), e);
	  	} catch(IOException e) {
	  		logger.error(e.getMessage(), e);
	  	}	
	  		
  		return;
  	}
  	
  	if ((oper != null) && oper.equals("del")) {
  		int ret = Customer.allcoDistrict(udistrict);
  		responseMessage(ret, "", response);
  		return;
  	}

  	
  	
  	JSONArray cs = Customer.getDistrictCustomerStat(udistrict);

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", cs.length());
  		retval.put("rows", cs);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}	
  }

  private void customerQuery(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("cid");
  	JSONObject retval = null;

  	Customer c = Customer.getCustomerByID(cid);
  	try {
  		if (c != null) {
	  		retval = c.toJSON();
	  		retval.put("code", 0);
	  	} else {
	  		retval = new JSONObject();
	  		retval.put("code", -1);
	  	}
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  public void init() throws ServletException {
  	try {
  		bundleMsg.load(XingServlet.class.getResourceAsStream("Msg.properties"));
  	} catch (IOException e) {
  		throw new ServletException(e.getMessage());
  	}
  }

  //action=9
  private void allocInfo(HttpServletRequest request, HttpServletResponse response) {
  	String month = request.getParameter("id");
  	String oper = request.getParameter("oper");
  	JSONObject retval = new JSONObject();
  	JSONArray cs;

  	if ((oper != null) && oper.equals("excel")) {
  		DBUtil.getAllocInfoExcel(response);
  		return;
  	}

  	if (month == null)
  		cs = DBUtil.getAllocInfo();
  	else
  		cs = DBUtil.getAllocSubInfo(month);

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", cs.length());
  		retval.put("rows", cs);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  //action=19
  private void allocDistrictInfo(HttpServletRequest request, HttpServletResponse response) {
  	String udistrict = (String) request.getSession().getAttribute("udistrict");
  	String oper = request.getParameter("oper");

  	if ((oper != null) && oper.equals("excel")) {
  		DBUtil.getAllocDistrictInfoExcel(udistrict, response);
  		return;
  	}

  	JSONObject retval = new JSONObject();
  	JSONArray cs = DBUtil.getAllocDistrictInfo(udistrict);

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", cs.length());
  		retval.put("rows", cs);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }
  

  private void xgUserManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		xgUserAll(request, response);
  	else if (oper.equals("add"))
  		xgUserAdd(request, response);
  	else if (oper.equals("edit"))
  		xgUserEdit(request, response);
  	else if (oper.equals("del"))
  		xgUserDel(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void xgUserAll(HttpServletRequest request, HttpServletResponse response) {
  	JSONObject retval = new JSONObject();
  	JSONArray sa = DBUtil.xgUserAll();

  	try {
  		JSONObject userData = new JSONObject();
  		userData.put("uprof", (String)request.getSession().getAttribute("uprof"));
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", sa.length());
  		retval.put("rows", sa);
  		retval.put("userData", userData);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void xgUserAdd(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("uid");
  	String uname = request.getParameter("uname");
  	String upass = request.getParameter("upass");
  	String prof = request.getParameter("prof");

  	int r = DBUtil.xgUserAdd(uid, uname, upass, prof);
  	if (r == 0)
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(r, "internal error", response);
  }

  private void xgUserEdit(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("uid");
  	String uname = request.getParameter("uname");
  	String upass = request.getParameter("upass");
  	String prof = request.getParameter("prof");

  	int r = DBUtil.xgUserEdit(uid, uname, upass, prof);
  	if (r == 0)
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(r, "internal error", response);
  }

  private void xgUserDel(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("id");

  	if (DBUtil.xgUserDel(uid))
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void govuserManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		govuserAll(request, response);
  	else if (oper.equals("add"))
  		govuserAdd(request, response);
  	else if (oper.equals("edit"))
  		govuserEdit(request, response);
  	else if (oper.equals("del"))
  		govuserDel(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void govuserAll(HttpServletRequest request, HttpServletResponse response) {
  	String  uid=(String) request.getSession().getAttribute("uid");
  	String district = (String) request.getSession().getAttribute("udistrict");
  	String uname = (String)request.getSession().getAttribute("uname");
  	JSONObject retval = new JSONObject();
  	JSONObject userData = new JSONObject();
  	JSONArray sa = DBUtil.getAllGovuser(district);

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", sa.length());
  		retval.put("rows", sa);
  		userData.put("udistrict", district);
  		userData.put("usid", (String)request.getSession().getAttribute("usid"));
  		userData.put("uname", uname);
  		retval.put("userdata", userData);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void govuserAdd(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("uid");
  	String uname = request.getParameter("uname");
  	String upass = request.getParameter("upass");
  	String district = request.getParameter("district");
  	String sid = request.getParameter("sid");
  	if (district == null)
  		district = (String)request.getSession().getAttribute("udistrict");

  	if (isEmpty(uid)||isEmpty(uname)||isEmpty(upass)||isEmpty(district)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	int r = DBUtil.govuserAdd(uid, uname, upass, district, sid);
  	if (r == 0)
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(r, "internal error", response);
  }

  private void govuserEdit(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("uid");
  	String uname = request.getParameter("uname");
  	String upass = request.getParameter("upass");
  	String district = request.getParameter("district");
  	String sid = request.getParameter("sid");
  	if (district == null)
  		district = (String)request.getSession().getAttribute("udistrict");

  	if (isEmpty(uid)||isEmpty(uname)||isEmpty(upass)||isEmpty(district)) {
  		responseMessage(1, bundleMsg.getProperty("INPUT_NULL"), response);
  		return;
  	}

  	if (DBUtil.govuserEdit(uid,uname,upass,district,sid))
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void govuserDel(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("id");

  	if (DBUtil.govuserDel(uid))
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void changePass(HttpServletRequest request, HttpServletResponse response) {
  	String uid = (String)request.getSession().getAttribute("uid");
  	String udis = (String)request.getSession().getAttribute("udistrict");
  	String oldPass = request.getParameter("oldPass");
  	String newPass = request.getParameter("newPass");
  	Hashtable hu;

  	if (udis != null)
  		hu = DBUtil.govUserLogin(uid, oldPass);
  	else
  		hu = DBUtil.xgUserLogin(uid, oldPass);

  	if (hu.isEmpty()) {
  		responseMessage(1, "wrong old password", response);
		return;
  	}

  	if (DBUtil.changePass(udis, uid, newPass) == 1)
  		responseMessage(0, "password changed", response);
  	else
  		responseMessage(-1, "action failed", response);
  }

  private void userLogin(HttpServletRequest request, HttpServletResponse response) {
  	String uid = request.getParameter("username");
	String upass = request.getParameter("userpass");
	String veryCode= request.getParameter("veryCode");
	String fruit = request.getParameter("fruit");

	String oldCode=(String) request.getSession().getAttribute("validateCode");
	if (!veryCode.equals(oldCode)) {
		responseMessage(2, "veryCode error", response);
		return;
	}

	Hashtable hu = fruit.equals("1")? DBUtil.govUserLogin(uid, upass):DBUtil.xgUserLogin(uid, upass);
	if (hu.isEmpty()) {
		responseMessage(1, "uname or upass error", response);
		logger.warn("*****  uid: " + uid + " upass: " + upass + "  login failed! ***** ");
		return;
	}

	logger.info("uid: " + uid + " login!");
	Enumeration e = hu.keys();
	HttpSession session = request.getSession();
	while(e.hasMoreElements()) {
		String key = (String)e.nextElement();
		String val = (String)hu.get(key);
		session.setAttribute(key, val);
	}
	session.setAttribute("uid", uid);

	if (fruit.equals("2")) {
		responseMessage(0, "kefu-open.html", response);
		return;
	}

	String udis = (String)session.getAttribute("udistrict");
	String usid = (String)session.getAttribute("usid");
	if (udis.equals("0"))
		responseMessage(0, "minzhengju-open.html", response);
	else if (usid.equals("0"))
		responseMessage(0, "quminzhengju-open.html", response);
	else
		responseMessage(0, "jiedao-open.html", response);
  }

  //action=13
  private void companyManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null)
  		companyAll(request, response);
  	else if (oper.equals("add"))
  		companyAdd(request, response);
  	else if (oper.equals("edit"))
  		companyEdit(request, response);
  	else if (oper.equals("del"))
  		companyDel(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }

  private void companyAll(HttpServletRequest request, HttpServletResponse response) {
  	JSONObject retval = new JSONObject();
  	JSONArray sa = Company.getAllCompany();

  	try {
  		retval.put("page", 1);
  		retval.put("total", 1);
  		retval.put("records", sa.length());
  		retval.put("rows", sa);
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }

  private void companyAdd(HttpServletRequest request, HttpServletResponse response) {
  	String comname = request.getParameter("comname");
  	String comid = request.getParameter("id");
  	String qualify = request.getParameter("qualify");
  	String district = request.getParameter("district");

  	if (Company.companyAdd(comid,comname,qualify,district))
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void companyEdit(HttpServletRequest request, HttpServletResponse response) {
  	String comname = request.getParameter("comname");
  	String comid = request.getParameter("id");
  	String qualify = request.getParameter("qualify");
  	String district = request.getParameter("district");

  	if (Company.companyEdit(comid,comname,qualify,district))
  		responseMessage(0, "ok", response);
  	else
  		responseMessage(2, "internal error", response);
  }

  private void companyDel(HttpServletRequest request, HttpServletResponse response) {
  	String comid = request.getParameter("id");
  	int n = Company.companyDelete(comid);

  	responseMessage(n, "ok", response);
  }

  //action=20
  private void userExit(HttpServletRequest request, HttpServletResponse response) {
  	String  uid=(String) request.getSession().getAttribute("uid");

  	request.getSession().invalidate();
  	logger.info("uid: " + uid + " logout!");
  	responseMessage(0, "/", response);
  }

  private void validateCode(HttpServletRequest request, HttpServletResponse response) {
  	ValidateService.findValidate(request, response);
  }
  
  //action=22
  private void quitCustomerManage(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("id");
  	String p0  = request.getParameter("0");
  	int r = 0;
  	
  	if (p0.equals("restore"))
  		r = Customer.restoreCustomerByID(cid);
  	else if (p0.equals("death"))
  		r = Customer.deleteQuitCustomer(cid);
  	
  	responseMessage(r, "ok", response);
  }
  
  //action=23
  private void netMapManage(HttpServletRequest request, HttpServletResponse response) {
  	String oper = request.getParameter("oper");

  	if (oper == null) {
  		JSONObject retval = new JSONObject();
	  	JSONArray sa = DBUtil.getAllNetMap();
	
	  	try {
	  		retval.put("page", 1);
	  		retval.put("total", 1);
	  		retval.put("records", sa.length());
	  		retval.put("rows", sa);
	  		response.getWriter().print(retval);
	  		response.getWriter().close();
	  	} catch(JSONException e) {
	  		logger.error(e.getMessage(), e);
	  	} catch(IOException e) {
	  		logger.error(e.getMessage(), e);
	  	}
  	}else if (oper.equals("add")) {
  		String nid   = request.getParameter("nid");
  		String nname = request.getParameter("nname");
  		String pname = request.getParameter("pname");
  		
  		int retval = DBUtil.netMapAdd(nid, nname, pname);
  		responseMessage(retval, "", response);
  	}else if (oper.equals("set")) {
  		String nid = request.getParameter("nid");
  		String px = request.getParameter("px");
  		String py = request.getParameter("py");
  		
  		int retval = DBUtil.netMapSetPosition(nid, px, py);
  		responseMessage(retval, "", response);
  	}else if (oper.equals("edit"))
  		xgUserEdit(request, response);
  	else if (oper.equals("del"))
  		xgUserDel(request, response);
  	else
  		responseMessage(1, "Invalid oper paremeter!", response);
  }
  
  //action=24
  private void queryCustomerByTel(HttpServletRequest request, HttpServletResponse response) {
  	String tel = request.getParameter("tel");
  	JSONObject retval = null;

  	Customer c = Customer.getCustomerByTel(tel);
  	try {
  		if (c != null) {
	  		retval = c.toJSON();
	  		retval.put("code", 0);
	  	} else {
	  		retval = new JSONObject();
	  		retval.put("code", -1);
	  	}
  		response.getWriter().print(retval);
  		response.getWriter().close();
  	} catch(JSONException e) {
  		logger.error(e.getMessage(), e);
  	} catch(IOException e) {
  		logger.error(e.getMessage(), e);
  	}
  }
  
  //action=26
  private void zeroAccount(HttpServletRequest request, HttpServletResponse response) {
  	String district = (String) request.getSession().getAttribute("udistrict");

  	int retval = Customer.zeroAccount(district);
  	responseMessage(retval, "", response);
  }
  
  //action = 27
  private void updateCustomerRemark(HttpServletRequest request, HttpServletResponse response) {
  	String cid = request.getParameter("cid");
  	String remark = request.getParameter("remark");
  	
  	int retval = Customer.updateRemark(cid, remark);
  	responseMessage(retval, "", response);
  }

  /*
  ** Utils
  */
  private boolean isEmpty(final String str) {
  	if (str == null)
  		return true;
  	else if (str.trim().length() == 0)
  	  return true;
  	else
  	  return false;
  }

  private void sendSMSofAssignTask(String cmobile, String smobile, String cmsg, String smsg) {
  	SmsWebService service = new SmsWebService();
	SmsWebServicePortType port = service.getSmsWebServiceHttpPort();
	try {
		if (cmobile.length() == 11)
			port.send("liushigang", "4CFFC8A8B97F9A3DCE3F056B2609F284", "", cmobile, java.net.URLEncoder.encode(cmsg, "utf-8"));
		port.send("liushigang", "4CFFC8A8B97F9A3DCE3F056B2609F284", "", smobile, java.net.URLEncoder.encode(smsg, "utf-8"));
	} catch(Exception e) {}
  }

  private void sendOneSMS(String mobile, String msg) {
  	SmsWebService service = new SmsWebService();
	SmsWebServicePortType port = service.getSmsWebServiceHttpPort();
	try {
		port.send("liushigang", "4CFFC8A8B97F9A3DCE3F056B2609F284", "", mobile, java.net.URLEncoder.encode(msg, "utf-8"));
	} catch(Exception e) {}
  }

  //build a html select of waiter name-mobile pair in jqgrid form edit select
  //action=11
  private void buildWaiterSelect(HttpServletResponse response) {
  	JSONArray sa = Waiter.getAllWaiterByCom();

	try{
	  	response.setContentType("text/json;charset=UTF-8");
	  	response.getWriter().print(sa);
	  	response.getWriter().close();
	} catch(Exception e) {
		logger.error(e.getMessage(), e);
	}
  }

  //action=14
  private void buildCompanySelect(HttpServletResponse response) {
  	try{
  		String sel = "<select>" + Company.buildCompanySelect() + "</select>";

	  	response.setContentType("text/plain;charset=UTF-8");
	  	response.getWriter().print(sel);
	  	response.getWriter().close();
	} catch(Exception e) {
		logger.error(e.getMessage(), e);
	}
  }

  private void debugParameters(HttpServletRequest request) {
	  	if (!logger.isDebugEnabled())
	  		return;

	  	StringBuffer sb = new StringBuffer("Parameters -  ");
	  	java.util.Enumeration keys = request.getParameterNames();
	  	while (keys.hasMoreElements()) {
	  		String para = (String)keys.nextElement();
	  		String value = request.getParameter(para);
	  		sb.append(para).append('=').append(value).append(',');
	  	}
	  	logger.debug(sb.toString());
	}
}